package com.asion.qkan.utils.retrofitCache;

import android.text.TextUtils;

import com.asion.qkan.jiguangtuisong.ExampleApplication;

import java.io.File;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by asion on 16-10-6.
 */

public class SetCacheUtils {

    //注释掉的是 有无网络都先读取缓存

    static Interceptor interceptor =(chain)->{

//        Request request = chain.request();
//        if (!StringsUtil.isNetworkConnected(ExampleApplication.context)) {
//            request = request.newBuilder()
//                    .cacheControl(CacheControl.FORCE_CACHE)
//                    .build();
//        }
//
//        Response response = chain.proceed(request);
//        if (StringsUtil.isNetworkConnected(ExampleApplication.context)) {
//            int maxAge = 0 * 60; // 有网络时 设置缓存超时时间0个小时
//            response.newBuilder()
//                    .header("Cache-Control", "public, max-age=" + maxAge)
//                    .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
//                    .build();
//        } else {
//            int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
//            response.newBuilder()
//                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
//                    .removeHeader("Pragma")
//                    .build();
//        }
//        return response;

        Request request = chain.request();
        okhttp3.Response response = chain.proceed(request);

        String cacheControl = request.cacheControl().toString();
        if (TextUtils.isEmpty(cacheControl)) {
            cacheControl = "public, max-age=60";
        }
        return response.newBuilder()
                .header("Cache-Control", cacheControl)
                .removeHeader("Pragma")
                .build();
    };

    public static OkHttpClient setCache(){
        File httpCacheDirectory = new File(ExampleApplication.context.getCacheDir(), "responses");
        //设置缓存 50M
        Cache cache = new Cache(httpCacheDirectory, 50 * 1024 * 1024);
        //创建OkHttpClient，并添加拦截器和缓存代码
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(interceptor)
                .cache(cache).build();

//        File httpCacheDirectory = new File(ExampleApplication.context.getCacheDir(), "responses");
//        //设置缓存 10M
//        Cache cache = new Cache(httpCacheDirectory, 100 * 1024 * 1024);
//        OkHttpClient client = new OkHttpClient.Builder()
//                .addInterceptor(interceptor)
//                .cache(cache).build();
                return client;
    }
}
